package com.shouer.doc.ui.conversation;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.shouer.doc.R;
import com.shouer.doc.application.App;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.dialog.CommonDialogUtil;
import com.shouer.doc.dialog.ShouerLoadingDialogUtil;
import com.shouer.doc.event.RemoteLoginEvent;
import com.shouer.doc.event.RongRemoteLoginEvent;
import com.shouer.doc.ui.ShouerConversationFragment;
import com.shouer.doc.ui.conversation.dialog.SelectCardDialog;
import com.shouer.doc.ui.conversation.dialog.SelectCardDialogUtil;
import com.shouer.doc.ui.conversation.presenter.ConversionPresenterCompl;
import com.shouer.doc.ui.conversation.presenter.IConversationPresenter;
import com.shouer.doc.ui.conversation.response.PayControllerDocResponse;
import com.shouer.doc.ui.conversation.response.QueryLeftTimeResponse;
import com.shouer.doc.ui.conversation.view.ICoversionView;
import com.shouer.doc.ui.finishorder.FinishOrderActivity;
import com.shouer.doc.ui.login.LoginActivity;
import com.shouer.doc.ui.login.model.UserModel;
import com.shouer.doc.ui.main.MainActivity;
import com.shouer.doc.ui.neworder.model.SimpleOrderModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Collection;
import java.util.Iterator;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.callkit.RongCallAction;
import io.rong.callkit.RongVoIPIntent;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imlib.MessageTag;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.TypingMessage.TypingStatus;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Discussion;
import io.rong.imlib.model.PublicServiceProfile;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

/**
 * Created by yangyayun on 2016/11/9.
 */

public class ConversationActivity extends FragmentActivity implements RongIMClient.TypingStatusListener, ICoversionView, View.OnClickListener,SelectCardDialog.OnCardSelectListener{

    private App app;
    private final String TextTypingTitle = "对方正在输入...";
    private final String VoiceTypingTitle = "对方正在讲话...";

    public static final int SET_TEXT_TYPING_TITLE = 1;
    public static final int SET_VOICE_TYPING_TITLE = 2;
    public static final int SET_TARGET_ID_TITLE = 0;

    private SharedPreferences sp;
    /**
     * 是否是从会通知栏点击进来的
     */
    private boolean isFromPush = false;
    /**
     * 对方id
     */
    private String mTargetId;
    /**
     * 会话类型
     */
    private Conversation.ConversationType mConversationType;
    /**
     * title
     */
    private String title;
    protected ShouerConversationFragment fragment;

    @BindView(R.id.title_left)
    protected View btn_left;
    @BindView(R.id.title)
    protected TextView titleView;

    @BindView(R.id.top_patient_layout)
    protected ConversationPatientView patientView;

    @BindView(R.id.close_btn)
    protected View closeBtn;

    @BindView(R.id.rollback)
    protected View rollBackView;


    private SimpleOrderModel orderModel;
    private IConversationPresenter presenter;
    /**
     * 通过Message what更新被聊天用户的输入状态
     */
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case SET_TEXT_TYPING_TITLE:
                    setTitle(TextTypingTitle);
                    break;
                case SET_VOICE_TYPING_TITLE:
                    setTitle(VoiceTypingTitle);
                    break;
                case SET_TARGET_ID_TITLE:
                    setActionBarTitle(mConversationType, mTargetId);
                    break;
                default:
                    break;
            }
            return true;
        }
    });


    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_conversation_layout);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);// 使得音量键控制媒体声音
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        presenter = new ConversionPresenterCompl(this);
        app = (App) getApplicationContext();
        sp = getSharedPreferences("config", MODE_PRIVATE);
        Intent intent = getIntent();

        if (intent == null || intent.getData() == null)
            return;
        orderModel = (SimpleOrderModel) getIntent().getSerializableExtra("order_info");
        mTargetId = intent.getData().getQueryParameter("targetId");
        //intent.getData().getLastPathSegment();//获得当前会话类型
        mConversationType = Conversation.ConversationType.valueOf(intent.getData()
                .getLastPathSegment().toUpperCase(Locale.getDefault()));

        title = intent.getData().getQueryParameter("title");
        // android 6.0 以上版本，监听SDK权限请求，弹出对应请求框。
        if (Build.VERSION.SDK_INT >= 23) {
            RongIM.getInstance().setRequestPermissionListener(new RongIM.RequestPermissionsListener() {
                @RequiresApi(api = Build.VERSION_CODES.M)
                @Override
                public void onPermissionRequest(String[] permissions, final int requestCode) {
                    for (final String permission : permissions) {
                        if (shouldShowRequestPermissionRationale(permission)) {
                            requestPermissions(new String[]{permission}, requestCode);
                        } else {
                            int isPermissionGranted = checkSelfPermission(permission);
                            if (isPermissionGranted != PackageManager.PERMISSION_GRANTED) {
                                new AlertDialog.Builder(ConversationActivity.this)
                                        .setMessage("你需要在设置里打开以下权限:" + permission)
                                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                requestPermissions(new String[]{permission}, requestCode);
                                            }
                                        })
                                        .setNegativeButton("取消", null)
                                        .create().show();
                            }
                            return;
                        }
                    }
                }
            });
        }
        //设置用户输入状态监听
        RongIMClient.setTypingStatusListener(this);

        //isPushMessage(getIntent());
        initViews();
    }

    private void initViews() {
        if (mConversationType == Conversation.ConversationType.GROUP) {
            //如果是群组类型的会话 从上个页面中获取订单的信息（SimpleOrder或者订单编号）
            if (orderModel == null) {
                //如果orderModel为空的话则根据mTargetId查询订单信息
                ShouerLoadingDialogUtil.getInstance().show(getContext());
                patientView.fillPatientInfo(null);
                presenter.queryOrderInfo(mTargetId);
            } else {
                if (orderModel.getOrderState() == ShouerConst.ORDER_STATE_DOCTOR || orderModel.getOrderState() == ShouerConst.ORDER_STATE_DIAGNOSING) {
                    presenter.queryOrderInfo(mTargetId);
                } else {
                    patientView.fillPatientInfo(orderModel);
                    patientView.setVisibility(View.VISIBLE);
                    isPushMessage(getIntent());
                }
            }
        }
    }

    private void isPushMessage(Intent intent) {

        if (intent == null || intent.getData() == null)
            return;
        //push
        if (intent.getData().getScheme().equals("rong") && intent.getData().getQueryParameter("isFromPush") != null) {
            Log.d(ConversationActivity.class.getSimpleName(), "isFromPush------:" + "has isFromPush");
            //通过intent.getData().getQueryParameter("push") 为true，判断是否是push消息
            if (intent.getData().getQueryParameter("isFromPush").equals("true")) {
                Log.d(ConversationActivity.class.getSimpleName(), "isFromPush------:" + true);
                //只有收到系统消息和不落地 push 消息的时候，pushId 不为 null。而且这两种消息只能通过 server 来发送，客户端发送不了。
//                RongIM.getInstance().getRongIMClient().recordNotificationEvent(id);
                isFromPush = true;
                enterActivity();
            } else if (RongIM.getInstance().getCurrentConnectionStatus().equals(RongIMClient.ConnectionStatusListener.ConnectionStatus.DISCONNECTED)) {
                Log.d(ConversationActivity.class.getSimpleName(), "isFromPush------:" + "ConnectionStatus.DISCONNECTED");
                if (intent.getData().getPath().contains("conversation/system")) {
                    Log.d(ConversationActivity.class.getSimpleName(), "isFromPush------:" + "contains(\"conversation/system\"))");
                    Intent intent1 = new Intent(ConversationActivity.this, MainActivity.class);
                    intent1.putExtra("systemconversation", true);
                    startActivity(intent1);
                    finish();
                    return;
                }
                enterActivity();
            } else {
                if (intent.getData().getPath().contains("conversation/system")) {
                    Intent intent1 = new Intent(ConversationActivity.this, MainActivity.class);
                    intent1.putExtra("systemconversation", true);
                    startActivity(intent1);
                    finish();
                    return;
                }
                enterFragment(mConversationType, mTargetId);
            }
        } else {//不是从Push消息通知栏进入的
            //用户在健康汇客户端已登录
            if (app.isUserLogin()) {
                if (RongIM.getInstance().getCurrentConnectionStatus().equals(RongIMClient.ConnectionStatusListener.ConnectionStatus.DISCONNECTED)) {
                    enterActivity();
                } else {
                    enterFragment(mConversationType, mTargetId);
                }
            } else //用户在健康汇客户端未登录
            {
                startActivity(new Intent(ConversationActivity.this, LoginActivity.class));
                finish();
            }
        }
    }

    private void enterActivity() {
        String token = app.getRongToken();
        if (!app.isUserLogin()) {
            Log.e(ConversationActivity.class.getSimpleName() + "push", "push2");
            startActivity(new Intent(ConversationActivity.this, LoginActivity.class));
            finish();
        } else {
            Log.e(ConversationActivity.class.getSimpleName() + "push", "push2");
            reconnect(token);
        }
    }

    @Override
    public void onResume()
    {
        super.onResume();
        Log.i(ConversationActivity.class.getSimpleName(),"onResume()进入了");
        super.onResume();
        if (!app.isUserLogin())
        {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }else
        {
            if (RongIM.getInstance().getCurrentConnectionStatus().equals(RongIMClient.ConnectionStatusListener.ConnectionStatus.DISCONNECTED))
            {
                Log.i(ConversationActivity.class.getSimpleName(),"onResume()------断开连接 需要重新连接");
                presenter.reConnect(app.getRongToken());
            }else
            {
                Log.i(ConversationActivity.class.getSimpleName(),"onResume()------已经连接");
            }
        }
    }

    @Override
    public void onPause()
    {
        super.onPause();
        Log.i(ConversationActivity.class.getSimpleName(),"onPause()");
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        RongIM.getInstance().setRequestPermissionListener(null);
        RongIMClient.setTypingStatusListener(null);
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        presenter.onDeatroy();
    }


    @OnClick(value = {R.id.title_left, R.id.close_btn,R.id.kouka,R.id.rollback})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left:
                hintKbTwo();
                finish();
                break;
            case R.id.close_btn:
                if (null != orderModel) {
                    CommonDialogUtil.getInstance().showMessage(this, this, "要关闭该订单吗", "取消", "关闭", 0);
                }
                break;
            case R.id.rollback:
                CommonDialogUtil.getInstance().showMessage(this,this,"是否确认退单!","取消","确定",4);
                break;
            case R.id.dialog_left_btn:
                CommonDialogUtil.getInstance().dismiss();
                break;
            case R.id.dialog_right_btn:
                CommonDialogUtil.getInstance().dismiss();
                int tag= (int) view.getTag(R.id.dialog_btn_tag);
                if (tag==1)
                {
                    //送药扣卡
                    ShouerLoadingDialogUtil.getInstance().show(this);
                    presenter.payControllerDoc(orderModel.getOrderId(),"1","4",orderModel.getUserId(),getUserId(),"1");
                }else if (tag==2)
                {
                    //挂号扣卡
                    ShouerLoadingDialogUtil.getInstance().show(this);
                    presenter.payControllerDoc(orderModel.getOrderId(),"1","5",orderModel.getUserId(),getUserId(),"1");
                }else if (tag==4)
                {
                    presenter.rollBackOrder(orderModel.getOrderId());
                }else
                {
                    ShouerLoadingDialogUtil.getInstance().show(this);
                    presenter.closeOrder(orderModel.getPatId(), orderModel.getOrderId());
                }
                break;
            case R.id.kouka:
                SelectCardDialogUtil.getInstance().show(this,this);
                break;
        }
    }

    @Override
    public void onBackPressed() {

        ConversationFragment fragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.rong_content);
        if (!fragment.onBackPressed()) {
            if (isFromPush && app.isUserLogin()) {
                isFromPush = false;
                startActivity(new Intent(this, MainActivity.class));
            }
            finish();
        }
    }

    private void reconnect(String token) {

        RongIM.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                Log.e(ConversationActivity.class.getSimpleName(), "---onTokenIncorrect--");
            }

            @Override
            public void onSuccess(String s) {
                Log.i(ConversationActivity.class.getSimpleName(), "---onSuccess--" + s);
                Log.e("reconnect()", "push4");
                enterFragment(mConversationType, mTargetId);
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {
                Log.e(ConversationActivity.class.getSimpleName(), "---onError--" + e);
                enterFragment(mConversationType, mTargetId);
            }
        });

    }

    /**
     * 加载会话页面 ConversationFragment
     *
     * @param mConversationType 会话类型
     * @param mTargetId         会话 Id
     */
    private void enterFragment(Conversation.ConversationType mConversationType, String mTargetId) {

        setActionBarTitle(mConversationType, mTargetId);
        fragment = new ShouerConversationFragment();

        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath("conversation").appendPath(mConversationType.getName().toLowerCase())
                .appendQueryParameter("targetId", mTargetId).build();

        fragment.setUri(uri);
        if (orderModel.getOrderState() == ShouerConst.ORDER_STATE_EVALUATED || orderModel.getOrderState() == ShouerConst.ORDER_STATE_CLOSED) {
            fragment.setShowRongExtension(false);
        }

        //诊断中展示回退按钮
        if (orderModel.getOrderState() == ShouerConst.ORDER_STATE_DIAGNOSING)
        {
            rollBackView.setVisibility(View.VISIBLE);
        }

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //xxx 为你要加载的 id
        transaction.add(R.id.rong_content, fragment);
        transaction.commitAllowingStateLoss();

        if (orderModel!=null&&orderModel.getOrderType()==ShouerConst.ORDER_TYPE_YAO)
        {
            presenter.queryUserInfo();
        }
    }


    /**
     * 设置会话页面 Title
     *
     * @param conversationType 会话类型
     * @param targetId         目标 Id
     */
    private void setActionBarTitle(Conversation.ConversationType conversationType, String targetId) {

        if (conversationType == null)
            return;

        if (conversationType.equals(Conversation.ConversationType.PRIVATE)) {
            setPrivateActionBar(targetId);
        } else if (conversationType.equals(Conversation.ConversationType.GROUP)) {
            setGroupActionBar(targetId);
        } else if (conversationType.equals(Conversation.ConversationType.DISCUSSION)) {
            setDiscussionActionBar(targetId);
        } else if (conversationType.equals(Conversation.ConversationType.CHATROOM)) {
            setTitle(title);
        } else if (conversationType.equals(Conversation.ConversationType.SYSTEM)) {
            setTitle(R.string.actionbar_system);
        } else if (conversationType.equals(Conversation.ConversationType.APP_PUBLIC_SERVICE)) {
            setAppPublicServiceActionBar(targetId);
        } else if (conversationType.equals(Conversation.ConversationType.PUBLIC_SERVICE)) {
            setPublicServiceActionBar(targetId);
        } else if (conversationType.equals(Conversation.ConversationType.CUSTOMER_SERVICE)) {
            setTitle(R.string.main_customer);
        } else {
            setTitle(R.string.actionbar_sub_defult);
        }

    }

    /**
     * 设置私聊界面 ActionBar
     */
    private void setPrivateActionBar(String targetId) {
        if (!TextUtils.isEmpty(title)) {
            setTitle(title);
        } else {
            setTitle(targetId);
        }
    }

    /**
     * 设置群聊界面 ActionBar
     *
     * @param targetId 会话 Id
     */
    private void setGroupActionBar(String targetId) {
        if (!TextUtils.isEmpty(title)) {
            setTitle(title);
        }
    }

    /**
     * 设置讨论组界面 ActionBar
     */
    private void setDiscussionActionBar(String targetId) {

        if (targetId != null) {

            RongIM.getInstance().getDiscussion(targetId
                    , new RongIMClient.ResultCallback<Discussion>() {
                        @Override
                        public void onSuccess(Discussion discussion) {
                            setTitle(discussion.getName());
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode e) {
                            if (e.equals(RongIMClient.ErrorCode.NOT_IN_DISCUSSION)) {
                                setTitle("不在讨论组中");
                                supportInvalidateOptionsMenu();
                            }
                        }
                    });
        } else {
            setTitle("讨论组");
        }
    }

    /**
     * 设置应用公众服务界面 ActionBar
     */
    private void setAppPublicServiceActionBar(String targetId) {
        if (targetId == null)
            return;

        RongIM.getInstance().getPublicServiceProfile(Conversation.PublicServiceType.APP_PUBLIC_SERVICE
                , targetId, new RongIMClient.ResultCallback<PublicServiceProfile>() {
                    @Override
                    public void onSuccess(PublicServiceProfile publicServiceProfile) {
                        setTitle(publicServiceProfile.getName());
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });
    }

    /**
     * 设置公共服务号 ActionBar
     */
    private void setPublicServiceActionBar(String targetId) {

        if (targetId == null)
            return;


        RongIM.getInstance().getPublicServiceProfile(Conversation.PublicServiceType.PUBLIC_SERVICE
                , targetId, new RongIMClient.ResultCallback<PublicServiceProfile>() {
                    @Override
                    public void onSuccess(PublicServiceProfile publicServiceProfile) {
                        setTitle(publicServiceProfile.getName());
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(String title) {
        titleView.setText(title);
    }

    /**
     * 设置标题
     *
     * @param titleId
     */
    public void setTitle(int titleId) {
        titleView.setText(titleId);
    }

    /**
     * 用户输入状态监听回调方法
     */
    @Override
    public void onTypingStatusChanged(Conversation.ConversationType type, String targetId, Collection<TypingStatus> typingStatusSet) {
        //当输入状态的会话类型和targetID与当前会话一致时，才需要显示
        if (type.equals(mConversationType) && targetId.equals(mTargetId)) {
            int count = typingStatusSet.size();
            //count表示当前会话中正在输入的用户数量，目前只支持单聊，所以判断大于0就可以给予显示了
            if (count > 0) {
                Iterator iterator = typingStatusSet.iterator();
                TypingStatus status = (TypingStatus) iterator.next();
                String objectName = status.getTypingContentType();

                MessageTag textTag = TextMessage.class.getAnnotation(MessageTag.class);
                MessageTag voiceTag = VoiceMessage.class.getAnnotation(MessageTag.class);
                //匹配对方正在输入的是文本消息还是语音消息
                if (objectName.equals(textTag.value())) {
                    mHandler.sendEmptyMessage(SET_TEXT_TYPING_TITLE);
                } else if (objectName.equals(voiceTag.value())) {
                    mHandler.sendEmptyMessage(SET_VOICE_TYPING_TITLE);
                }
            } else {//当前会话没有用户正在输入，标题栏仍显示原来标题
                mHandler.sendEmptyMessage(SET_TARGET_ID_TITLE);
            }
        }
    }

    /**
     * 关闭输入法对话框
     */
    private void hintKbTwo() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 501) {
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
            if (fragment == null || !fragment.onBackPressed()) {
                if (isFromPush) {
                    isFromPush = false;
                    startActivity(new Intent(this, MainActivity.class));
                }
                finish();

                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public App getApp() {
        return app;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void closeOrderSuccess(String orderId, String extend) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        if (TextUtils.isEmpty(extend) || extend.equals("0")) {
            Toast.makeText(ConversationActivity.this, "关闭订单成功", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Intent intent = new Intent(this, FinishOrderActivity.class);
            intent.putExtra("extend", extend);
            startActivity(intent);
            finish();
        }

    }

    @Override
    public void closeOrderFailed(String fialInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        closeBtn.setClickable(true);
        Toast.makeText(ConversationActivity.this, fialInfo, Toast.LENGTH_SHORT).show();
    }

    /**
     * 订单回退成功
     * */
    @Override
    public void rollBackOrderSuccess(String orderId) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(ConversationActivity.this,"订单回退成功",Toast.LENGTH_SHORT).show();
        finish();
    }

    /**
     * 订单回退失败
     * */
    @Override
    public void rollBackOrderFailed(String failInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(ConversationActivity.this,failInfo,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void queryOrderSuccess(SimpleOrderModel orderModel) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Log.d(ConversationActivity.class.getSimpleName(), "查询订单消息成功：" + orderModel.toString());
        this.orderModel = orderModel;

        if (orderModel.getOrderType() == ShouerConst.ORDER_TYPE_YAO) {
            title = getResources().getString(R.string.ORDER_NAME_YAO);//挂号送药
        } else if (orderModel.getOrderType() == ShouerConst.ORDER_TYPE_SHIPING) {
            title = getResources().getString(R.string.ORDER_NAME_SHIPING);//视频咨询
        } else if (orderModel.getOrderType() == ShouerConst.ORDER_TYPE_DIANHUA) {
            title = getResources().getString(R.string.ORDER_NAME_DIANHUA);//电话咨询
        } else {
            if (orderModel.getChannel()==9)
            {
                title = getResources().getString(R.string.ORDER_NAME_HEALTHRECORD);//健康报告咨询
            }else {
                if ("0".equals(orderModel.getFreeType())) {
                    title = getResources().getString(R.string.ORDER_NAME_TUWEN_FREE);//免费导诊
                } else {
                    title = getResources().getString(R.string.ORDER_NAME_TUWEN);//图文咨询
                }
            }
        }
        titleView.setText(title);

        patientView.fillPatientInfo(orderModel);
        patientView.setVisibility(View.VISIBLE);
        isPushMessage(getIntent());

    }

    @Override
    public void queryOrderFailed(String failInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        patientView.loadDetailFailed();
    }

    /**
     * 查询剩余时间成功
     * */
    @Override
    public void queryLeftTimeSuccess(QueryLeftTimeResponse response) {
        ShouerLoadingDialogUtil.getInstance().dismiss();

        /**
         * 转跳到视频通话页面
         * */
        Intent intent = new Intent(RongVoIPIntent.RONG_INTENT_ACTION_VOIP_SINGLEVIDEO);
        intent.putExtra("conversationType", Conversation.ConversationType.PRIVATE.getName().toLowerCase());
        intent.putExtra("targetId", getTargetUserId());
        intent.putExtra("orderId",getOrderId());
        intent.putExtra("patId",getPatId());
        intent.putExtra("callAction", RongCallAction.ACTION_OUTGOING_CALL.getName());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setPackage(getPackageName());
        startActivity(intent);
    }

    /**
     * 查询剩余时间失败
     * */
    @Override
    public void queryLeftTimeFailed(String failInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(this,failInfo,Toast.LENGTH_SHORT).show();
    }

    @Override
    public String getUserId() {
        if (null!=orderModel)
        {
            return orderModel.getUserId();
        }
        return null;
    }

    @Override
    public void queryUserFailed(String failInfo) {
        Log.e(ConversationActivity.class.getSimpleName(),failInfo);
    }

    @Override
    public void queryUserSuccess(UserModel userModel) {
        if (null!=userModel)
        {
            if (userModel.getLeftTime01()>0||userModel.getLeftTime03()>0)
            {
                patientView.showVIP();
            }

            if ((userModel.getLeftTime04()>0||userModel.getLeftTime05()>0)&&
                        orderModel.getOrderType()==ShouerConst.ORDER_TYPE_YAO&&
                        orderModel.getOrderState()==ShouerConst.ORDER_STATE_DIAGNOSING)
            {
                patientView.showKouka();
            }

            if (orderModel.getOrderType()==ShouerConst.ORDER_TYPE_YAO)
            {
                patientView.setUserBalance(userModel.getBalance());

            }

        }
    }

    /**
     * 健康卡扣卡成功
     * */
    @Override
    public void payControllerDocSuccess(PayControllerDocResponse response) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(this,"扣卡成功",Toast.LENGTH_SHORT).show();
    }

    /**
     * 健康卡扣卡失败
     * */
    @Override
    public void payControllerDocFailed(String failInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(ConversationActivity.this,failInfo,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void close() {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RemoteLoginEvent event) {
        finish();
    }

    /**
     * 账号异地登录 关闭Activity
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RongRemoteLoginEvent event) {
        finish();
    }

    public String getTargetUserId() {

        return orderModel.getUserId();
    }

    public String getOrderId() {
        return orderModel.getOrderId();
    }

    public String getPatId() {
        return orderModel.getPatId();
    }

    public void onVideoClick()
    {
        Log.i(ConversationActivity.class.getSimpleName(),"onVideoClick");
        if (null!=orderModel)
        {
            presenter.queryOrderLeftTime(orderModel.getOrderId());
        }
    }

    @Override
    public void onCardSelected(int cardType) {
        SelectCardDialogUtil.getInstance().dismiss();
        if (cardType==0)
        {
            //送药扣卡
            SelectCardDialogUtil.getInstance().dismiss();
            CommonDialogUtil.getInstance().showMessage(this,this,"首儿送药扣卡","取消","确定",1);
        }else if (cardType==1)
        {
            //挂号扣卡
            SelectCardDialogUtil.getInstance().dismiss();
            CommonDialogUtil.getInstance().showMessage(this,this,"首儿挂号扣卡","取消","确定",2);
        }
    }
}
